<template>
  <div class="source-table-config">
    <div v-for="(dbConfig, dbIndex) in sourceConfig.databases" :key="dbIndex" class="database-config-item">
      <el-card shadow="never" class="db-card">
        <template #header>
          <div class="card-header">
            <span>数据库配置 {{ dbIndex + 1 }}</span>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              circle
              @click="removeDatabase(dbIndex)"
              :disabled="sourceConfig.databases.length <= 1"
            />
          </div>
        </template>

        <el-form :model="dbConfig" label-width="120px">
          <el-form-item label="数据库" required>
            <el-select
              v-model="dbConfig.database_name"
              placeholder="请选择数据库"
              :filterable="true"
              :clearable="true"
              :loading="databasesLoading"
              style="width: 100%"
              popper-class="batch-dialog-select-popper"
              popper-append-to-body
              @change="() => handleDatabaseChange(dbIndex)"
            >
              <el-option
                v-for="db in databasesList"
                :key="db"
                :label="db"
                :value="db"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择表" required>
            <el-select
              v-model="dbConfig.table_names"
              placeholder="请选择表（可多选）"
              :filterable="true"
              :clearable="true"
              :loading="tablesLoading[dbIndex]"
              multiple
              style="width: 100%"
              popper-class="batch-dialog-select-popper"
              popper-append-to-body
              @change="() => handleTablesChange(dbIndex)"
            >
              <el-option
                v-for="table in tablesList[dbIndex]"
                :key="table.id"
                :label="table.table_name"
                :value="table.table_name"
              >
                <div class="option-line">
                  <span>{{ table.table_name }}</span>
                  <span v-if="table.table_comment" class="option-comment">
                    {{ table.table_comment }}
                  </span>
                </div>
              </el-option>
            </el-select>
            <div class="form-tip">可以选择多个表，系统将自动合并统计</div>
          </el-form-item>
        </el-form>
      </el-card>

      <div v-if="dbConfig.table_names && dbConfig.table_names.length > 0" class="tables-config">
        <div v-for="(tableName, tableIndex) in dbConfig.table_names" :key="`${dbIndex}-${tableName}`" class="table-config-item">
          <el-card shadow="never" class="table-card">
            <template #header>
              <div class="card-header">
                <span>{{ dbConfig.database_name }}.{{ tableName }}</span>
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click="removeTable(dbIndex, tableIndex)"
                  :disabled="dbConfig.table_names.length <= 1"
                />
              </div>
            </template>

            <el-form :model="getTableConfig(dbIndex, tableName)" label-width="120px">
              <el-form-item label="是否去重">
                <el-switch
                  v-model="getTableConfig(dbIndex, tableName).use_distinct"
                  @change="handleDistinctSwitchChange(dbIndex, tableName)"
                />
                <div class="form-tip">开启后，SQL中将使用 DISTINCT 进行去重统计</div>
              </el-form-item>

              <el-form-item v-if="getTableConfig(dbIndex, tableName).use_distinct" label="去重字段">
                <el-select
                  v-model="getTableConfig(dbIndex, tableName).distinct_field"
                  placeholder="请选择去重字段"
                  :filterable="true"
                  :clearable="true"
                  :loading="tableFieldsLoading[`${dbIndex}-${tableName}`]"
                  style="width: 100%"
                  popper-class="batch-dialog-select-popper"
                  popper-append-to-body
                  @change="handleTableConfigChange"
                >
                  <el-option
                    v-for="fieldItem in tableFieldsList[`${dbIndex}-${tableName}`]"
                    :key="fieldItem.field_name"
                    :label="fieldItem.field_name"
                    :value="fieldItem.field_name"
                  >
                    <div class="option-line">
                      <span>{{ fieldItem.field_name }}</span>
                      <span v-if="fieldItem.column_comment" class="option-comment">
                        {{ fieldItem.column_comment }}
                      </span>
                    </div>
                  </el-option>
                </el-select>
                <div class="form-tip">用于去重统计的字段，如：product_id</div>
              </el-form-item>

              <el-form-item v-if="globalTimeRange.time_range_type !== 'all'" label="时间字段">
                <el-select
                  v-model="getTableConfig(dbIndex, tableName).time_field"
                  placeholder="请选择时间字段"
                  :filterable="true"
                  :clearable="true"
                  :loading="tableFieldsLoading[`${dbIndex}-${tableName}`]"
                  style="width: 100%"
                  popper-class="batch-dialog-select-popper"
                  popper-append-to-body
                  @change="handleTableConfigChange"
                >
                  <el-option
                    v-for="fieldItem in tableFieldsList[`${dbIndex}-${tableName}`]"
                    :key="fieldItem.field_name"
                    :label="fieldItem.field_name"
                    :value="fieldItem.field_name"
                  >
                    <div class="option-line">
                      <span>{{ fieldItem.field_name }}</span>
                      <span v-if="fieldItem.column_comment" class="option-comment">
                        {{ fieldItem.column_comment }}
                      </span>
                    </div>
                  </el-option>
                </el-select>
                <div class="form-tip">用于时间过滤的字段，如：etl_date</div>
              </el-form-item>

              <!-- 表级别的过滤条件和统计字段配置 -->
              <el-divider />
              <el-row :gutter="16" class="table-filter-toggle-row" style="margin-top: 16px;">
                <el-col :span="12">
                  <el-form-item label="启用过滤">
                    <el-switch 
                      v-model="getTableConfig(dbIndex, tableName)._filterEnabled" 
                      @change="handleTableFilterToggleChange(dbIndex, tableName)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="启用统计字段">
                    <el-switch 
                      v-model="getTableConfig(dbIndex, tableName)._statEnabled" 
                      @change="handleTableStatToggleChange(dbIndex, tableName)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 筛选条件配置 -->
              <template v-if="getTableConfig(dbIndex, tableName)._filterEnabled">
                <el-divider />
                <div class="section-subtitle" style="margin-bottom: 12px;">
                  <el-icon><Filter /></el-icon>
                  <span>筛选条件（可选）</span>
                </div>
                <div v-for="(condition, conditionIndex) in (getTableConfig(dbIndex, tableName).filter_conditions || [])" :key="conditionIndex" class="filter-condition-row">
                  <el-row :gutter="16">
                    <el-col :span="6">
                      <el-form-item :label="conditionIndex === 0 ? '字段' : ''" label-width="60px">
                        <el-select
                          v-model="condition.field"
                          placeholder="选择字段"
                          :loading="tableFieldsLoading[`${dbIndex}-${tableName}`]"
                          filterable
                          style="width: 100%"
                          popper-class="batch-dialog-select-popper"
                          popper-append-to-body
                          @change="emitChange"
                        >
                          <el-option
                            v-for="field in (tableFieldsList[`${dbIndex}-${tableName}`] || [])"
                            :key="field.field_name"
                            :label="field.field_name"
                            :value="field.field_name"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item :label="conditionIndex === 0 ? '操作符' : ''" label-width="60px">
                        <el-select
                          v-model="condition.operator"
                          placeholder="操作符"
                          style="width: 100%"
                          popper-class="batch-dialog-select-popper"
                          popper-append-to-body
                          @change="emitChange"
                        >
                          <el-option label="=" value="=" />
                          <el-option label="!=" value="!=" />
                          <el-option label=">" value=">" />
                          <el-option label="<" value="<" />
                          <el-option label=">=" value=">=" />
                          <el-option label="<=" value="<=" />
                          <el-option label="IN" value="IN" />
                          <el-option label="LIKE" value="LIKE" />
                          <el-option label="NOT LIKE" value="NOT LIKE" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item :label="conditionIndex === 0 ? '值' : ''" label-width="60px">
                        <el-input
                          v-model="condition.value"
                          placeholder="输入值"
                          @change="emitChange"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item label-width="0">
                        <el-button
                          type="danger"
                          size="small"
                          @click="removeTableFilterCondition(dbIndex, tableName, conditionIndex)"
                        >
                          删除
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
                <el-button
                  type="primary"
                  size="small"
                  :icon="Plus"
                  @click="addTableFilterCondition(dbIndex, tableName)"
                >
                  添加筛选条件
                </el-button>
              </template>

              <!-- 统计字段配置 -->
              <template v-if="getTableConfig(dbIndex, tableName)._statEnabled">
                <el-divider />
                <div class="section-subtitle" style="margin-bottom: 12px;">
                  <el-icon><DataAnalysis /></el-icon>
                  <span>统计字段（可选）</span>
                </div>
                <el-form-item>
                  <StatFieldsConfig
                    :model-value="getTableConfig(dbIndex, tableName).stat_fields"
                    :available-fields="(tableFieldsList[`${dbIndex}-${tableName}`] || []).map((f) => f.field_name)"
                    @update:model-value="(val) => handleTableStatFieldsChange(dbIndex, tableName, val)"
                  />
                </el-form-item>
              </template>
            </el-form>
          </el-card>
        </div>
      </div>
    </div>

    <el-button type="primary" :icon="Plus" class="add-btn" @click="addDatabase">
      添加数据库
    </el-button>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Plus, Filter, DataAnalysis } from '@element-plus/icons-vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'
import StatFieldsConfig from './StatFieldsConfig.vue'

const componentLogger = createLogger('SourceTableConfig')

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ databases: [] })
  },
  dataSourceId: {
    type: [Number, String],
    default: null
  },
  globalTimeRange: {
    type: Object,
    default: () => ({
      time_range_type: 'all',
      time_start: null,
      time_end: null
    })
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const createDatabaseConfig = () => ({
  database_name: '',
  table_names: [],
  tables: []
})

const createDefaultConfig = () => ({
  data_source_id: props.dataSourceId ?? null,
  time_range_type: props.globalTimeRange?.time_range_type ?? 'all',
  time_start: props.globalTimeRange?.time_start ?? null,
  time_end: props.globalTimeRange?.time_end ?? null,
  databases: [createDatabaseConfig()]
})

const normalizeDatabases = (databases) => {
  if (!Array.isArray(databases) || databases.length === 0) {
    return [createDatabaseConfig()]
  }
  return databases.map((db) => ({
    database_name: db?.database_name || '',
    table_names: Array.isArray(db?.table_names) ? db.table_names : [],
    tables: Array.isArray(db?.tables) ? db.tables : []
  }))
}

const sourceConfig = ref(createDefaultConfig())
const databasesList = ref([])
const tablesList = ref({})
const tableFieldsList = ref({})
const databasesLoading = ref(false)
const tablesLoading = ref({})
const tableFieldsLoading = ref({})

const initializeExistingSelections = () => {
  if (!props.dataSourceId) return
  if (!Array.isArray(sourceConfig.value.databases)) return
  sourceConfig.value.databases.forEach((db, dbIndex) => {
    if (db?.database_name) {
      fetchTables(dbIndex).then(() => {
        if (Array.isArray(db?.table_names)) {
          db.table_names.forEach((tableName) => {
            if (tableName) {
              fetchTableFields(dbIndex, tableName)
            }
          })
        }
      })
    }
  })
}

const buildPayload = () => {
  const payload = {
    ...sourceConfig.value,
    data_source_id: props.dataSourceId ?? sourceConfig.value.data_source_id ?? null,
    time_range_type: props.globalTimeRange?.time_range_type ?? sourceConfig.value.time_range_type ?? 'all',
    time_start: props.globalTimeRange?.time_start ?? sourceConfig.value.time_start ?? null,
    time_end: props.globalTimeRange?.time_end ?? sourceConfig.value.time_end ?? null,
    databases: normalizeDatabases(sourceConfig.value.databases)
  }
  return JSON.parse(JSON.stringify(payload))
}

const emitChange = () => {
  const payload = buildPayload()
  componentLogger.debug('[SourceTableConfig] emit payload', payload)
  emit('update:modelValue', payload)
  emit('change', payload)
}

const addDatabase = (shouldEmit = true) => {
  if (!sourceConfig.value.databases) {
    sourceConfig.value.databases = []
  }
  sourceConfig.value.databases.push(createDatabaseConfig())
  if (shouldEmit) emitChange()
}

const removeDatabase = (dbIndex) => {
  if (sourceConfig.value.databases.length <= 1) {
    ElMessage.warning('至少需要保留一个数据库配置')
    return
  }
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (dbConfig.table_names) {
    dbConfig.table_names.forEach((tableName) => {
      delete tableFieldsList.value[`${dbIndex}-${tableName}`]
      delete tableFieldsLoading.value[`${dbIndex}-${tableName}`]
    })
  }
  delete tablesList.value[dbIndex]
  delete tablesLoading.value[dbIndex]
  sourceConfig.value.databases.splice(dbIndex, 1)
  emitChange()
}

const removeTable = (dbIndex, tableIndex) => {
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (!dbConfig || !dbConfig.table_names) return
  if (dbConfig.table_names.length <= 1) {
    ElMessage.warning('至少需要保留一个表')
    return
  }
  const tableName = dbConfig.table_names[tableIndex]
  dbConfig.table_names.splice(tableIndex, 1)
  if (dbConfig.tables) {
    dbConfig.tables = dbConfig.tables.filter((t) => t.table_name !== tableName)
  }
  delete tableFieldsList.value[`${dbIndex}-${tableName}`]
  delete tableFieldsLoading.value[`${dbIndex}-${tableName}`]
  emitChange()
}

const getTableConfig = (dbIndex, tableName) => {
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (!dbConfig) return null
  if (!dbConfig.tables) {
    dbConfig.tables = []
  }
  let tableConfig = dbConfig.tables.find((t) => t.table_name === tableName)
  if (!tableConfig) {
    tableConfig = {
      table_name: tableName,
      use_distinct: false,
      distinct_field: '',
      time_field: 'etl_date',
      filter_conditions: [],
      stat_fields: {},
      _filterEnabled: false,
      _statEnabled: false
    }
    dbConfig.tables.push(tableConfig)
  }
  // 确保新属性存在（向后兼容）
  if (tableConfig.filter_conditions === undefined) {
    tableConfig.filter_conditions = []
  }
  if (tableConfig.stat_fields === undefined) {
    tableConfig.stat_fields = {}
  }
  if (tableConfig._filterEnabled === undefined) {
    tableConfig._filterEnabled = !!(tableConfig.filter_conditions && tableConfig.filter_conditions.length > 0)
  }
  if (tableConfig._statEnabled === undefined) {
    tableConfig._statEnabled = !!(tableConfig.stat_fields && Object.keys(tableConfig.stat_fields).length > 0)
  }
  return tableConfig
}

const handleDistinctSwitchChange = (dbIndex, tableName) => {
  const tableConfig = getTableConfig(dbIndex, tableName)
  if (!tableConfig) return
  if (tableConfig.use_distinct) {
    const key = `${dbIndex}-${tableName}`
    if (!tableFieldsList.value[key] || tableFieldsList.value[key].length === 0) {
      fetchTableFields(dbIndex, tableName)
    }
  } else {
    tableConfig.distinct_field = ''
  }
  emitChange()
}

const fetchDatabases = async () => {
  const dataSourceId = props.dataSourceId
  if (!dataSourceId) {
    databasesList.value = []
    return
  }
  try {
    databasesLoading.value = true
    const response = await api.get('/reports/starrocks-databases', {
      params: { config_id: dataSourceId }
    })
    if (response.data.success) {
      databasesList.value = response.data.data || []
      componentLogger.info('数据库列表加载成功', { count: databasesList.value.length })
    } else {
      ElMessage.error(response.data.message || '获取数据库列表失败')
    }
  } catch (error) {
    componentLogger.error('获取数据库列表失败', error)
    ElMessage.error('获取数据库列表失败')
  } finally {
    databasesLoading.value = false
  }
}

const fetchTables = async (dbIndex) => {
  const dataSourceId = props.dataSourceId
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (!dbConfig) return
  const databaseName = dbConfig.database_name
  if (!dataSourceId || !databaseName) {
    tablesList.value[dbIndex] = []
    return
  }
  try {
    tablesLoading.value[dbIndex] = true
    const response = await api.get('/reports/starrocks-tables', {
      params: { config_id: dataSourceId, database: databaseName }
    })
    if (response.data.success) {
      tablesList.value[dbIndex] = response.data.data || []
      componentLogger.info('表列表加载成功', {
        database: databaseName,
        count: tablesList.value[dbIndex].length
      })
    } else {
      ElMessage.error(response.data.message || '获取表列表失败')
    }
  } catch (error) {
    componentLogger.error('获取表列表失败', error)
    ElMessage.error('获取表列表失败')
  } finally {
    tablesLoading.value[dbIndex] = false
  }
}

const fetchTableFields = async (dbIndex, tableName) => {
  const dataSourceId = props.dataSourceId
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (!dbConfig || !tableName) return
  const databaseName = dbConfig.database_name
  if (!dataSourceId || !databaseName) return
  const key = `${dbIndex}-${tableName}`
  try {
    tableFieldsLoading.value[key] = true
    const response = await api.get('/reports/starrocks-table-fields', {
      params: { config_id: dataSourceId, database: databaseName, table_name: tableName }
    })
    if (response.data.success) {
      tableFieldsList.value[key] = response.data.data || []
      componentLogger.info(`表 ${databaseName}.${tableName} 字段列表加载成功`, {
        count: tableFieldsList.value[key].length
      })
    } else {
      ElMessage.error(response.data.message || '获取字段列表失败')
    }
  } catch (error) {
    componentLogger.error('获取字段列表失败', error)
    ElMessage.error('获取字段列表失败')
  } finally {
    tableFieldsLoading.value[key] = false
  }
}

const handleDatabaseChange = (dbIndex) => {
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (!dbConfig) return
  dbConfig.table_names = []
  dbConfig.tables = []
  tablesList.value[dbIndex] = []
  emitChange()
  fetchTables(dbIndex)
}

const handleTablesChange = (dbIndex) => {
  const dbConfig = sourceConfig.value.databases[dbIndex]
  if (!dbConfig) return
  dbConfig.tables = dbConfig.tables?.filter((tableConfig) => dbConfig.table_names.includes(tableConfig.table_name)) || []
  dbConfig.table_names.forEach((tableName) => {
    fetchTableFields(dbIndex, tableName)
  })
  emitChange()
}

// 表级别的过滤条件相关函数
const addTableFilterCondition = (dbIndex, tableName) => {
  const tableConfig = getTableConfig(dbIndex, tableName)
  if (!tableConfig) return
  if (!tableConfig.filter_conditions) {
    tableConfig.filter_conditions = []
  }
  tableConfig.filter_conditions.push({
    field: '',
    operator: '=',
    value: ''
  })
  tableConfig._filterEnabled = true
  emitChange()
}

const removeTableFilterCondition = (dbIndex, tableName, conditionIndex) => {
  const tableConfig = getTableConfig(dbIndex, tableName)
  if (!tableConfig || !tableConfig.filter_conditions) return
  tableConfig.filter_conditions.splice(conditionIndex, 1)
  if (tableConfig.filter_conditions.length === 0) {
    tableConfig._filterEnabled = false
  }
  emitChange()
}

const handleTableFilterToggleChange = (dbIndex, tableName) => {
  const tableConfig = getTableConfig(dbIndex, tableName)
  if (!tableConfig) return
  // 确保 _filterEnabled 属性存在
  if (tableConfig._filterEnabled === undefined) {
    tableConfig._filterEnabled = false
  }
  if (tableConfig._filterEnabled) {
    if (!tableConfig.filter_conditions || tableConfig.filter_conditions.length === 0) {
      if (!tableConfig.filter_conditions) {
        tableConfig.filter_conditions = []
      }
      tableConfig.filter_conditions.push({
        field: '',
        operator: '=',
        value: ''
      })
    }
  } else {
    tableConfig.filter_conditions = []
  }
  emitChange()
}

// 表级别的统计字段相关函数
const handleTableStatFieldsChange = (dbIndex, tableName, statFields) => {
  const tableConfig = getTableConfig(dbIndex, tableName)
  if (!tableConfig) return
  tableConfig.stat_fields = statFields
  emitChange()
}

const handleTableStatToggleChange = (dbIndex, tableName) => {
  const tableConfig = getTableConfig(dbIndex, tableName)
  if (!tableConfig) return
  // 确保 _statEnabled 属性存在
  if (tableConfig._statEnabled === undefined) {
    tableConfig._statEnabled = false
  }
  if (!tableConfig._statEnabled) {
    tableConfig.stat_fields = {}
  }
  emitChange()
}

const handleTableConfigChange = () => {
  emitChange()
}

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && typeof newVal === 'object') {
      const cloned = JSON.parse(JSON.stringify(newVal))
      cloned.databases = normalizeDatabases(cloned.databases)
      sourceConfig.value = {
        ...createDefaultConfig(),
        ...cloned
      }
      // 确保每个表配置的开关状态正确初始化（响应式）
      sourceConfig.value.databases.forEach((db, dbIndex) => {
        if (db.table_names && db.tables) {
          db.table_names.forEach((tableName) => {
            const tableConfig = getTableConfig(dbIndex, tableName)
            if (tableConfig) {
              if (tableConfig._filterEnabled === undefined) {
                tableConfig._filterEnabled = !!(tableConfig.filter_conditions && tableConfig.filter_conditions.length > 0)
              }
              if (tableConfig._statEnabled === undefined) {
                tableConfig._statEnabled = !!(tableConfig.stat_fields && Object.keys(tableConfig.stat_fields || {}).length > 0)
              }
            }
          })
        }
      })
    } else {
      sourceConfig.value = createDefaultConfig()
    }
    initializeExistingSelections()
  },
  { immediate: true, deep: true }
)

watch(
  () => props.dataSourceId,
  (id) => {
    sourceConfig.value.data_source_id = id ?? null
    fetchDatabases()
    emitChange()
  },
  { immediate: true }
)

watch(
  () => props.globalTimeRange,
  (val) => {
    if (val) {
      sourceConfig.value.time_range_type = val.time_range_type ?? sourceConfig.value.time_range_type ?? 'all'
      sourceConfig.value.time_start = val.time_start ?? null
      sourceConfig.value.time_end = val.time_end ?? null
      emitChange()
    }
  },
  { deep: true }
)

onMounted(() => {
  if (!sourceConfig.value.databases || sourceConfig.value.databases.length === 0) {
    addDatabase(false)
  }
})
</script>

<style scoped>
.db-card,
.table-card {
  margin-bottom: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option-line {
  display: flex;
  justify-content: space-between;
}

.option-comment {
  color: #8492a6;
  font-size: 12px;
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.tables-config {
  margin-bottom: 12px;
}

.add-btn {
  width: 100%;
  margin-top: 12px;
}
</style>
